const httpNet = require("./httpUtil.js");
const app = getApp();
function loginx(that,cb) {
	console.log("去登陆....");
	// let uuid = wx.getStorageSync("uid");
	// console.log(uuid);
	// if(uuid){
	// 	httpNet.reqGet('xwx/getUserInfoByUid',{id:uuid},function(r){
	// 		console.log(r);
	// 	});
	// }
	// 获取登陆凭证
	wx.login({
		success(res) {
			if (res.code) {
				// 获取用户信息;
				wx.getUserInfo({
					withCredentials: true,
					success: data => {
						console.log(data);
						//app.globalData.userInfo = res.userInfo
						wx.showLoading({
							title: '正在登陆',
						});
						wx.request({
							url: httpNet.path + 'xwx/getWxUserInfo',
							data: { code: res.code, iv: data.iv, encryptedData: data.encryptedData },
							method: 'post',
							header: {
								'Content-Type': 'application/x-www-form-urlencoded'
							},
							success: function (res) {
								
								console.log(res);
								if (res.header['wxToken']) {
									wx.setStorage({
										key: 'wxToken',
										data: res.header['wxToken']
									})
								}
								//取出来返回的数据的id放在缓存中,标识是当前用户的id
								var dat = res.data;
								if (dat.resultCode === 1000) {
									wx.setStorage({
										key: 'uid',
										data: dat.returnObject.id
									});
									wx.setStorage({
										key: 'user',
										data: dat.returnObject
									});
									that.setData({
										userInfo: data.userInfo,
										hasUserInfo: true,
                    islogin:true
									});
									wx.showToast({
										title: '登录成功',
										icon: 'success',
										duration: 1000
									});
									if(cb){
										return typeof cb == "function" && cb(res.data)
									}
								} else {
									wx.hideLoading();
									wx.showToast({
										title: '登录失败',
										icon: 'none',
										duration: 2000
									});
									that.setData({
										userInfo: false,
										hasUserInfo: false
									});
									wx.clearStorage();
								}
							},
							fail: function () {
								wx.showToast({
									title: '登录失败',
									icon: 'none',
									duration: 2000
								});
								wx.hideLoading();
								that.setData({
									userInfo: false,
									hasUserInfo: false
								});
								wx.clearStorage();
							}
						})
					},
					fail: data => {
						console.log(res);
						wx.hideLoading();
					}
				})
			} else {
				wx.hideLoading();
				console.log('登录失败！' + res.errMsg)
			}
		}
	})
}
module.exports = {
	loginx: loginx,
}